package com.lv.service.ui

import android.annotation.SuppressLint
import android.text.*
import android.text.method.DigitsKeyListener
import android.view.View
import android.view.inputmethod.EditorInfo
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.lv.common.base.BaseActivity
import com.lv.common.utils.ARoutUtils
import com.lv.common.utils.StatusBarUtil
import com.lv.common.utils.showToast
import com.lv.common.widget.keyboard.KeyboardUtil
import com.lv.service.R
import com.lv.service.databinding.ActivityInputCommonBinding

/**
 * 作者： ygx
 * 创建日期：2023/5/6 1:35 PM
 * 签名： 天行健，君子以自强不息；地势坤，君子以厚德载物。
 * -    _              _           _     _   ____  _             _ _
 * -   / \   _ __   __| |_ __ ___ (_) __| | / ___|| |_ _   _  __| (_) ___
 * -  / _ \ | '_ \ / _` | '__/ _ \| |/ _` | \___ \| __| | | |/ _` | |/ _ \
 * - / ___ \| | | | (_| | | | (_) | | (_| |  ___) | |_| |_| | (_| | | (_) |
 * -/_/   \_\_| |_|\__,_|_|  \___/|_|\__,_| |____/ \__|\__,_|\__,_|_|\___/
 * <p>
 * You never know what you can do until you try !
 * ----------------------------------------------------------------
 * 描述：公共输入页面
 */
@Route(path = ARoutUtils.InputCommonActivity)
class InputCommonActivity : BaseActivity<ActivityInputCommonBinding>(),
    View.OnClickListener {
    @Autowired(name = "title")//标题
    @JvmField
    var mTitle: String = ""

    @Autowired(name = "content")//内容
    @JvmField
    var mContent: String = ""

    @Autowired(name = "hint")//提示
    @JvmField
    var mHint: String = ""

    @Autowired(name = "length")//content长度
    @JvmField
    var mLength: Int = -1

    @Autowired(name = "dec")//描述
    @JvmField
    var mDec: String = ""

    @Autowired(name = "subitText")//提交文字
    @JvmField
    var mSubitText: String = "保存"

    @Autowired(name = "inputState")
    @JvmField
    var INPUT_STATE: INPUT_ENUM? = INPUT_ENUM.NOMAL

    override fun getLayoutRes() = R.layout.activity_input_common
    override fun initView() {
        super.initView()
        initStatusBar(this, true, true)
        ARouter.getInstance().inject(this)
        mBinding.apply {
            StatusBarUtil.setHeightAndPadding(this@InputCommonActivity, titleBar)
            titleBar.onClickBackIcon { finish() }
            tvSumbit.setOnClickListener(this@InputCommonActivity)
            ivClear.setOnClickListener(this@InputCommonActivity)
        }
    }

    @SuppressLint("ClickableViewAccessibility")
    override fun initConfig() {
        super.initConfig()
        mBinding.titleBar.setTitle(mTitle)
        if (mHint.isEmpty()) {
            mHint = "请输入$mTitle"
        }
        mBinding.etContent.hint = mHint
        mBinding.tvDec.hint = mDec
        mBinding.tvSumbitText.text = mSubitText
        mBinding.etContent.setText(mContent)

        if (mLength != -1) {
            mBinding.etContent.filters = arrayOf<InputFilter>(InputFilter.LengthFilter(mLength))
        }

        when (INPUT_STATE) {
            INPUT_ENUM.SINGLE -> {
                mBinding.etContent.maxLines = 1
                mBinding.etContent.ellipsize = TextUtils.TruncateAt.END
                if (mContent.isNotEmpty()) {
                    mBinding.ivClear.visibility = View.VISIBLE
                } else {
                    mBinding.ivClear.visibility = View.GONE
                }
                mBinding.etContent.isSingleLine = true
                mBinding.etContent.imeOptions = EditorInfo.IME_ACTION_DONE

            }
            INPUT_ENUM.NUMBER -> {
                mBinding.etContent.inputType = InputType.TYPE_CLASS_NUMBER
            }
            INPUT_ENUM.PHONE -> {
                mBinding.etContent.inputType = InputType.TYPE_CLASS_NUMBER
                mBinding.etContent.filters = arrayOf<InputFilter>(InputFilter.LengthFilter(11))
                if (mContent.isNotEmpty()) {
                    mBinding.ivClear.visibility = View.VISIBLE
                } else {
                    mBinding.ivClear.visibility = View.GONE
                }
            }
            INPUT_ENUM.INPUT_TOTAL -> {//输入计数
                mBinding.tvTotal.visibility = View.VISIBLE
                mBinding.tvTotal.text = "${mContent.length}/500"
                mBinding.etContent.addTextChangedListener(object : TextWatcher {
                    override fun beforeTextChanged(
                        s: CharSequence?,
                        start: Int,
                        count: Int,
                        after: Int
                    ) {

                    }

                    override fun onTextChanged(
                        s: CharSequence?,
                        start: Int,
                        before: Int,
                        count: Int
                    ) {
                        if (s.isNullOrEmpty() || s.isEmpty()) {
                            mBinding.tvTotal.text = "0/500"
                        } else {
                            mBinding.tvTotal.text = "${s.length}/500"
                        }
                    }

                    override fun afterTextChanged(s: Editable?) {

                    }
                })
            }
            INPUT_ENUM.NUMB_CHAT -> {//数字和字母
                mBinding.etContent.transformationMethod = null
                mBinding.etContent.keyListener = object : DigitsKeyListener() {
                    override fun getInputType(): Int {
                        return InputType.TYPE_TEXT_VARIATION_PASSWORD
                    }

                    override fun getAcceptedChars(): CharArray {
                        return "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray()
                    }
                }
            }
            INPUT_ENUM.IDENTIFICATION -> {//社会统一信用代码  “I、O、Z、S、V” 不得编入统一信用代码。
//                mBinding.etContent.transformationMethod = null
                mBinding.etContent.maxLines = 1
////                mBinding.etContent.imeOptions= EditorInfo.IME_ACTION_NEXT
                val digists = "0123456789ABCDEFGHJKLMNPQRTUWXY"
                mBinding.etContent.keyListener = DigitsKeyListener.getInstance(digists)
//                mBinding.etContent.keyListener = object : DigitsKeyListener() {
//                    override fun getInputType(): Int {
////                        return InputType.TYPE_TEXT_VARIATION_PASSWORD or InputType.TYPE_TEXT_FLAG_CAP_CHARACTERS
//                        return InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_NORMAL
//                    }
//
//                    override fun getAcceptedChars(): CharArray {
//                        return "0123456789ABCDEFGHJKLMNPQRTUWXY".toCharArray()
//                    }
//                }

                mBinding.etContent.setOnTouchListener { _, _ ->
                    keyboardUtil = KeyboardUtil(
                        this,
                        mBinding.etContent,
                        mBinding.llKeyboard,
                        mBinding.keyboardView
                    )
                    keyboardUtil?.hideSoftInputMethod()
                    keyboardUtil?.showKeyboard()
//                    keyboardUtil?.changeKeyboard(true)
                    false
                }

                mBinding.clContainer.setOnClickListener {
                    keyboardUtil?.hideKeyboard()
                }
            }

            else -> {

            }

        }
    }

    private var keyboardUtil: KeyboardUtil? = null


    override fun initData() {
        super.initData()

    }

    override fun initEvents() {
        super.initEvents()
        mBinding.etContent.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {

            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                if (INPUT_STATE == INPUT_ENUM.PHONE || INPUT_STATE == INPUT_ENUM.SINGLE) {
                    if (s != null && s.isNotEmpty()) {
                        mBinding.ivClear.visibility = View.VISIBLE
                    } else {
                        mBinding.ivClear.visibility = View.GONE
                    }
                }
                if (s != null && s.isNotEmpty()) {
                    mBinding.tvSumbitText.alpha = 1.0f
                    mBinding.tvSumbit.isEnabled = true
                } else {
                    mBinding.tvSumbitText.alpha = 0.2f
                    mBinding.tvSumbit.isEnabled = false
                }

            }

            override fun afterTextChanged(s: Editable?) {
            }
        })
    }

    override fun onClick(p0: View?) {
        when (p0?.id) {
            R.id.tv_sumbit -> {
                val content = mBinding.etContent.text.toString().trim()
                if (INPUT_STATE == INPUT_ENUM.IDENTIFICATION && content.length < 15) {
                    showToast("输入的统一社会信用代码有误")
                    return
                }
                intent.putExtra("content", content)
                setResult(RESULT_OK, intent)
                finish()
            }
            R.id.iv_clear -> {
                mBinding.etContent.text.clear()
                mBinding.ivClear.visibility = View.GONE
                mContent=""
            }

        }
    }


}

enum class INPUT_ENUM {
    SINGLE, NUMBER, NOMAL, PHONE, NUMB_CHAT, IDENTIFICATION, INPUT_TOTAL
}